package org.jeecg.modules.outOrderPt.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.modules.Inventory.entity.Inventory;
import org.jeecg.modules.Inventory.service.IInventoryService;
import org.jeecg.modules.basicSku.entity.BasicSku;
import org.jeecg.modules.basicSku.service.IBasicSkuService;
import org.jeecg.modules.basicSkuPt.entity.BasicSkuPt;
import org.jeecg.modules.basicSkuPt.service.IBasicSkuPtService;
import org.jeecg.modules.inOrder.service.IInOrderService;
import org.jeecg.modules.inOrder.service.IInOrderZiService;
import org.jeecg.modules.inOrderPt.service.IInOrderPtService;
import org.jeecg.modules.inOrderPt.service.IInOrderZiPtService;
import org.jeecg.modules.inventoryPt.entity.InventoryPt;
import org.jeecg.modules.inventoryPt.service.IInventoryPtService;
import org.jeecg.modules.operationLog.entity.OperationLog;
import org.jeecg.modules.operationLog.service.IOperationLogService;
import org.jeecg.modules.outOrder.entity.OutOrder;
import org.jeecg.modules.outOrder.entity.OutOrderZi;
import org.jeecg.modules.outOrder.vo.OutOrderPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.outOrderPt.entity.OutOrderZiPt;
import org.jeecg.modules.outOrderPt.entity.OutOrderPt;
import org.jeecg.modules.outOrderPt.vo.OutOrderPtPage;
import org.jeecg.modules.outOrderPt.service.IOutOrderPtService;
import org.jeecg.modules.outOrderPt.service.IOutOrderZiPtService;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: pt出库单
 * @Author: jeecg-boot
 * @Date: 2024-07-24
 * @Version: V1.0
 */
@Api(tags = "pt出库单")
@RestController
@RequestMapping("/outOrderPt/outOrderPt")
@Slf4j
public class OutOrderPtController {
    @Autowired
    private IOutOrderPtService outOrderPtService;
    @Autowired
    private IOutOrderZiPtService outOrderZiPtService;
    @Autowired
    private IInventoryPtService inventoryPtService;
    @Autowired
    private IOperationLogService operationLogService;
    @Autowired
    private IInOrderPtService inOrderPtService;
    @Autowired
    private IInOrderZiPtService inOrderZiPtService;
    @Autowired
    private IBasicSkuPtService basicSkuPtService;

    /**
     * 分页列表查询
     *
     * @param outOrderPt
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "pt出库单-分页列表查询")
    @ApiOperation(value = "pt出库单-分页列表查询", notes = "pt出库单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OutOrderPt outOrderPt,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OutOrderPt> queryWrapper = QueryGenerator.initQueryWrapper(outOrderPt, req.getParameterMap());
        if ((outOrderPt.getNum() != null && !outOrderPt.getNum().isEmpty()) || (outOrderPt.getSkucode() != null && !outOrderPt.getSkucode().isEmpty()) || (outOrderPt.getSkuname() != null && !outOrderPt.getSkuname().isEmpty()) || (outOrderPt.getCustomername() != null && !outOrderPt.getCustomername().isEmpty())) {
            LambdaQueryWrapper<OutOrderZiPt> wrapper = new LambdaQueryWrapper<>();
            if ((outOrderPt.getSkucode() != null && !outOrderPt.getSkucode().isEmpty())) {
                wrapper.eq(OutOrderZiPt::getCustomerSkuCode, outOrderPt.getSkucode());
            }
            if ((outOrderPt.getNum() != null && !outOrderPt.getNum().isEmpty())) {
                wrapper.eq(OutOrderZiPt::getNumber, outOrderPt.getNum());
            }
            if ((outOrderPt.getSkuname() != null && !outOrderPt.getSkuname().isEmpty())) {
                wrapper.eq(OutOrderZiPt::getSkuName, outOrderPt.getSkuname());
            }
            if ((outOrderPt.getCustomername() != null && !outOrderPt.getCustomername().isEmpty())) {
                wrapper.eq(OutOrderZiPt::getCustomer, outOrderPt.getCustomername());
            }
            List<String> ids = outOrderZiPtService.list(wrapper).stream().map(OutOrderZiPt::getOutOrderId).collect(Collectors.toList());
            if (ids.isEmpty()) {
                return Result.OK(new Page<OutOrder>());
            } else {
                queryWrapper.in("id", ids);
            }
        }
        Page<OutOrderPt> page = new Page<OutOrderPt>(pageNo, pageSize);
        IPage<OutOrderPt> pageList = outOrderPtService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @PostMapping("/confirm")
    public Result<?> confirm(@RequestBody OutOrderPt outOrderPt) {
        OutOrderPt byId = outOrderPtService.getById(outOrderPt.getId());
        if (byId == null) {
            return Result.error("未找到对应数据");
        }
        //if (byId.getStatus() == 0) {
        //    byId.setStatus(10);
        //    outOrderPtService.saveOrUpdate(byId);
        //    return Result.OK("确认成功", null);
        //}
        if (byId.getStatus() == 1) {
            return Result.error("该出库单已出库，请勿重复操作");
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<OutOrderZiPt> outOrderZis = outOrderZiPtService.selectByMainId(byId.getId());
        List<OperationLog> operationLogs = new ArrayList<>();
        List<InventoryPt> inventories = new ArrayList<>();
        for (OutOrderZiPt outOrderZi : outOrderZis) {
            String inventoryId = outOrderZi.getInventoryId();
            if (inventoryId != null && !inventoryId.isEmpty()) {
                Result<Object> result = getObjectResult(outOrderZi, inventoryId, user, operationLogs, inventories);
                if (result != null) return result;
            }
        }
        inventoryPtService.updateBatchById(inventories);
        byId.setStatus(1);
        byId.setRealname(user.getRealname());
        byId.setOutTime(new Date());
        outOrderPtService.updateById(byId);
        operationLogService.saveBatch(operationLogs);
        return Result.OK("出库成功", null);
    }

    @PostMapping("/getBoxNum")
    public Result<?> getBoxNum(@RequestBody JSONObject jsonObject) {
        String number = jsonObject.getString("number");
        String skuCode = jsonObject.getString("skuCode");
        String customerSkuCode = jsonObject.getString("customerSkuCode");
        BigDecimal numberBigDeimal = new BigDecimal(number);
        if (customerSkuCode != null && !customerSkuCode.isEmpty()) {
            BasicSkuPt one = basicSkuPtService.list(new LambdaQueryWrapper<BasicSkuPt>().eq(BasicSkuPt::getCustomerSkuCode, customerSkuCode)).get(0);
            if (one != null) {
                BigDecimal specificationsNumBigDeimal = new BigDecimal(one.getCkSpecificationsNum().toString());
                BigDecimal divide = numberBigDeimal.divide(specificationsNumBigDeimal, 2, RoundingMode.HALF_UP);
                return Result.OK(divide);
            }
        } else if (skuCode != null && !skuCode.isEmpty()) {
            BasicSkuPt one = basicSkuPtService.list(new LambdaQueryWrapper<BasicSkuPt>().eq(BasicSkuPt::getSkuCode, skuCode)).get(0);
            if (one != null) {
                BigDecimal specificationsNumBigDeimal = new BigDecimal(one.getCkSpecificationsNum().toString());
                BigDecimal divide = numberBigDeimal.divide(specificationsNumBigDeimal, 2, RoundingMode.HALF_UP);
                return Result.OK(divide);
            }
        }
        return Result.error("");
    }

    private @Nullable Result<Object> getObjectResult(OutOrderZiPt outOrderZiPt, String inventoryId, LoginUser user, List<OperationLog> operationLogs, List<InventoryPt> inventories) {
        InventoryPt inventory = inventoryPtService.getById(inventoryId);
        if (inventory.getStatus() == 1) {
            return Result.error("库存错误");
        }
        int stock = inventory.getNumber();
        int number = outOrderZiPt.getNumber();
        if (number > stock) {
            return Result.error("品番【" + outOrderZiPt.getCustomerSkuCode() + "】库存不足");
        }
        OperationLog operationLog = new OperationLog();
        int i = stock - number;
        BigDecimal numberBigDeimal = new BigDecimal(String.valueOf(i));
        BasicSkuPt one = basicSkuPtService.getOne(new LambdaQueryWrapper<BasicSkuPt>()
                .eq(BasicSkuPt::getCustomerSkuCode, outOrderZiPt.getCustomerSkuCode())
                .eq(BasicSkuPt::getCustomerName, outOrderZiPt.getCustomer()));
        BigDecimal specificationsNumBigDeimal = new BigDecimal(one.getCkSpecificationsNum().toString());
        BigDecimal divide = numberBigDeimal.divide(specificationsNumBigDeimal, 2, RoundingMode.HALF_UP);
        inventory.setBoxNum(divide.doubleValue());
        inventory.setNumber(i);
        inventory.setCkLength(outOrderZiPt.getLength());
        inventory.setCkWidth(outOrderZiPt.getWidth());
        inventory.setCkHeight(outOrderZiPt.getHeight());
        if (i <= 0) {
            inventory.setStatus(1);
        }
        operationLog.setNewNumber(i);
        operationLog.setSkuCode(outOrderZiPt.getSkuCode()).setSkuName(outOrderZiPt.getSkuName())
                .setNumber(outOrderZiPt.getNumber()).setOperationTime(new Date())
                .setOperationType("出库").setOperator(user.getRealname())
                .setLocation(outOrderZiPt.getLocation()).setInTime(outOrderZiPt.getInTime());
        operationLogs.add(operationLog);
        inventories.add(inventory);
        return null;
    }

    /**
     *   添加
     *
     * @param outOrderPtPage
     * @return
     */
    @AutoLog(value = "pt出库单-添加")
    @ApiOperation(value = "pt出库单-添加", notes = "pt出库单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody OutOrderPtPage outOrderPtPage) {
        List<OutOrderZiPt> outOrderZiList = outOrderPtPage.getOutOrderZiPtList();
        List<OutOrderZiPt> addList = new ArrayList<>();
        List<String> customerSkuCodes = outOrderZiList.stream().map(OutOrderZiPt::getCustomerSkuCode).collect(Collectors.toList());
        List<BasicSkuPt> list = basicSkuPtService.list(new LambdaQueryWrapper<BasicSkuPt>().in(BasicSkuPt::getCustomerSkuCode, customerSkuCodes));
        for (BasicSkuPt basicSkuPt : list) {
            for (OutOrderZiPt outOrderZiPt : outOrderZiList) {
                if (basicSkuPt.getCustomerSkuCode().equals(outOrderZiPt.getCustomerSkuCode())) {
                    outOrderZiPt.setFactoryCode(basicSkuPt.getSkuCode());
                }
            }
        }
        Set<String> skus = outOrderZiList.stream().map(OutOrderZiPt::getFactoryCode).collect(Collectors.toSet());
        LambdaQueryWrapper<InventoryPt> wrapper = Wrappers.lambdaQuery();
        wrapper.in(InventoryPt::getSkuCode, skus);
        wrapper.orderByAsc(InventoryPt::getInTime);
        List<InventoryPt> inventories = inventoryPtService.list(wrapper);

        for (String skuCode : outOrderZiList.stream().map(OutOrderZiPt::getFactoryCode).collect(Collectors.toSet())) {
            int outQuantity = outOrderZiList
                    .stream()
                    .filter(data -> Objects.equals(data.getFactoryCode(), skuCode))
                    .mapToInt(OutOrderZiPt::getNumber)
                    .sum();
            int inventoryQuantity = inventories
                    .stream()
                    .filter(data -> Objects.equals(data.getSkuCode(), skuCode))
                    .mapToInt(InventoryPt::getNumber)
                    .sum();
            Assert.isFalse(outQuantity > inventoryQuantity,
                    String.format("品番[%s]剩余库存数量[%s]，请勿多出", skuCode, inventoryQuantity));
        }

        Result<Object> result = getObjectResult(outOrderZiList, inventories, addList);
        if (result != null) return result;
        OutOrderPt outOrderPt = new OutOrderPt();
        BeanUtils.copyProperties(outOrderPtPage, outOrderPt);

        // 封装子表长宽高体积
        addList.stream().forEach(data->{
            String skuCode = data.getCustomerSkuCode();
            List<BasicSkuPt> basicSkuPtList = basicSkuPtService.list(new QueryWrapper<BasicSkuPt>().eq("customer_sku_code", skuCode));
            BasicSkuPt basicSkuPt = basicSkuPtList.stream().filter(a -> a.getCkLength() != null && a.getCkWidth() != null && a.getCkHeight() != null)
                    .collect(Collectors.toList()).get(0);
            data.setLength(basicSkuPt.getCkLength());
            data.setWidth(basicSkuPt.getCkWidth());
            data.setHeight(basicSkuPt.getCkHeight());
            data.setVolume(data.getLength().multiply(data.getWidth()).multiply(data.getHeight()).setScale(2,BigDecimal.ROUND_HALF_UP));
        });

        outOrderPtService.saveMain(outOrderPt, addList);
        return Result.OK("添加成功！");
    }

    private static @Nullable Result<Object> getObjectResult(List<OutOrderZiPt> outOrderZiList, List<InventoryPt> inventories, List<OutOrderZiPt> addList) {
        for (OutOrderZiPt outOrderZi : outOrderZiList) {
            Result<Object> result = getObjectResult(outOrderZi);
            if (result != null) return result;
            int number = outOrderZi.getNumber();
            String skuCode = outOrderZi.getFactoryCode();
            for (InventoryPt inventory : inventories) {
                if (!inventory.getSkuCode().equals(skuCode)) continue; // 确保处理相同SKU的库存
                    int stock = inventory.getNumber();
                if (stock == 0) continue;
                if (number >= stock) {// 如果待出库数量大于当前reportLabel对象的库存数量
                    number -= stock;
                    OutOrderZiPt outOrderZi1 = new OutOrderZiPt();
                    BeanUtils.copyProperties(outOrderZi, outOrderZi1);
                    outOrderZi1.setNumber(inventory.getNumber()).setLocation(inventory.getLocation())
                            .setInventoryId(inventory.getId()).setSkuName(inventory.getSkuName())
                            .setInventory(inventory.getNumber()).setInTime(inventory.getInTime());
                    addList.add(outOrderZi1);
                    stock = 0;
                } else {// 待出库数量小于当前reportLabel对象的库存数量
                    stock -= number;
                    OutOrderZiPt outOrderZi1 = new OutOrderZiPt();
                    BeanUtils.copyProperties(outOrderZi, outOrderZi1);
                    outOrderZi1.setNumber(number).setLocation(inventory.getLocation())
                            .setInventoryId(inventory.getId()).setSkuName(inventory.getSkuName())
                            .setInventory(inventory.getNumber()).setInTime(inventory.getInTime());
                    addList.add(outOrderZi1);
                    number = 0;
                }
                inventory.setNumber(stock);// 更新当前reportLabel对象的库存数量
                outOrderZi.setInventoryId(inventory.getId());
                if (number == 0) {// 如果待出库数量已经为0，则跳出循环
                    break;
                }
            }
        }
        return null;
    }

    private static @Nullable Result<Object> getObjectResult(OutOrderZiPt outOrderZi) {
        if (outOrderZi.getFactoryCode() == null || outOrderZi.getFactoryCode().isEmpty()) {
            return Result.error("入库单中【" + outOrderZi.getCustomerSkuCode() + "】品番不存在,若确认无误，请先维护品番数据");
        }
        return null;
    }

    /**
     *  编辑
     *
     * @param outOrderPtPage
     * @return
     */
    @AutoLog(value = "pt出库单-编辑")
    @ApiOperation(value = "pt出库单-编辑", notes = "pt出库单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OutOrderPtPage outOrderPtPage) {
        OutOrderPt outOrderPt = new OutOrderPt();
        BeanUtils.copyProperties(outOrderPtPage, outOrderPt);
        OutOrderPt outOrderPtEntity = outOrderPtService.getById(outOrderPt.getId());
        if (outOrderPtEntity == null) {
            return Result.error("未找到对应数据");
        }
        outOrderPtService.updateById(outOrderPt);
        outOrderZiPtService.updateBatchById(outOrderPtPage.getOutOrderZiPtList());
        return Result.OK("编辑成功!");
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "pt出库单-通过id删除")
    @ApiOperation(value = "pt出库单-通过id删除", notes = "pt出库单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        outOrderPtService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "pt出库单-批量删除")
    @ApiOperation(value = "pt出库单-批量删除", notes = "pt出库单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.outOrderPtService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "pt出库单-通过id查询")
    @ApiOperation(value = "pt出库单-通过id查询", notes = "pt出库单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OutOrderPt outOrderPt = outOrderPtService.getById(id);
        if (outOrderPt == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(outOrderPt);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "pt出库单子表通过主表ID查询")
    @ApiOperation(value = "pt出库单子表主表ID查询", notes = "pt出库单子表-通主表ID查询")
    @GetMapping(value = "/queryOutOrderZiPtByMainId")
    public Result<?> queryOutOrderZiPtListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<OutOrderZiPt> outOrderZiPtList = outOrderZiPtService.selectByMainId(id);
        return Result.OK(outOrderZiPtList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param outOrderPt
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OutOrderPt outOrderPt) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<OutOrderPt> queryWrapper = QueryGenerator.initQueryWrapper(outOrderPt, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<OutOrderPt> queryList = outOrderPtService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<OutOrderPt> outOrderPtList = new ArrayList<OutOrderPt>();
        if (oConvertUtils.isEmpty(selections)) {
            outOrderPtList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            outOrderPtList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<OutOrderPtPage> pageList = new ArrayList<OutOrderPtPage>();
        for (OutOrderPt main : outOrderPtList) {
            OutOrderPtPage vo = new OutOrderPtPage();
            BeanUtils.copyProperties(main, vo);
            List<OutOrderZiPt> outOrderZiPtList = outOrderZiPtService.selectByMainId(main.getId());
            vo.setOutOrderZiPtList(outOrderZiPtList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "pt出库单列表");
        mv.addObject(NormalExcelConstants.CLASS, OutOrderPtPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("pt出库单数据", "导出人:" + sysUser.getRealname(), "pt出库单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<OutOrderPtPage> list1 = ExcelImportUtil.importExcel(file.getInputStream(), OutOrderPtPage.class, params);
                for (OutOrderPtPage page : list1) {
                    List<OutOrderZiPt> outOrderZiList = page.getOutOrderZiPtList();
                    List<String> customerSkuCodes = outOrderZiList.stream().map(OutOrderZiPt::getCustomerSkuCode).collect(Collectors.toList());
                    List<BasicSkuPt> list2 = basicSkuPtService.list(new LambdaQueryWrapper<BasicSkuPt>().in(BasicSkuPt::getCustomerSkuCode, customerSkuCodes));
                    for (BasicSkuPt basicSkuPt : list2) {
                        for (OutOrderZiPt outOrderZiPt : outOrderZiList) {
                            if (basicSkuPt.getCustomerSkuCode().equals(outOrderZiPt.getCustomerSkuCode())) {
                                outOrderZiPt.setFactoryCode(basicSkuPt.getSkuCode());
                            }
                        }
                    }
                    List<OutOrderZiPt> addList = new ArrayList<>();
                    Set<String> skus = outOrderZiList.stream().map(OutOrderZiPt::getFactoryCode).collect(Collectors.toSet());
                    LambdaQueryWrapper<InventoryPt> wrapper = Wrappers.lambdaQuery();
                    wrapper.in(InventoryPt::getSkuCode, skus);
                    wrapper.orderByAsc(InventoryPt::getInTime);
                    wrapper.orderByAsc(InventoryPt::getStatus);
                    List<InventoryPt> inventories = inventoryPtService.list(wrapper);
                    List<OutOrderZiPt> summarizedList = outOrderZiList.stream()
                            .filter(outOrderZi -> outOrderZi.getCustomerSkuCode() != null)
                            .collect(Collectors.groupingBy(OutOrderZiPt::getCustomerSkuCode,
                                    Collectors.collectingAndThen(
                                            Collectors.toList(),
                                            (Function<List<OutOrderZiPt>, List<OutOrderZiPt>>) list -> { // 显式指定Function的输入输出类型
                                                if (list.isEmpty()) return Collections.emptyList();
                                                OutOrderZiPt representative = new OutOrderZiPt();
                                                BeanUtils.copyProperties(list.get(0), representative);
                                                representative.setNumber(list.stream().mapToInt(OutOrderZiPt::getNumber).sum());
                                                return Collections.singletonList(representative);
                                            })
                            ))
                            .values()
                            .stream()
                            .flatMap(List::stream)
                            .collect(Collectors.toList());
                    Result<Object> result = getObjectResult(summarizedList, inventories, addList);
                    if (result != null) return result;
                    OutOrderPt po = new OutOrderPt();
                    BeanUtils.copyProperties(page, po);
                    po.setOutTime(new Date());
                    outOrderPtService.saveMain(po, addList);
                }
                return Result.OK("文件导入成功！数据行数:" + list1.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
